package de.sonnemann_it.helden_software.heldenbogen.originalpdf;

import helden.plugin.HeldenPlugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class HeldenStart implements HeldenPlugin {

	DocumentBuilderFactory factory;

	private Action action;

	public HeldenStart() {

	}

	String[] dependantJars = { "itextpdf-5.1.2.jar", "ini4j-0.5.2.jar",
			"saxon9he.jar" };

	@Override
	public void doWork(JFrame frame) {
		List<String> neededJars = checkDependancies();

		if (neededJars.size() > 0) {
			int doDownload = JOptionPane
					.showConfirmDialog(
							frame,
							"Für die korrekte Funktionalität müssen ein paar Bibliotheken geladen werden.\n"
									+ "Soll dies jetzt getan werden?",
							"Download von Libs", JOptionPane.YES_NO_OPTION);
			if (doDownload == JOptionPane.YES_OPTION) {
				if (!downloadLibs(frame) || checkDependancies().size() != 0) {
					JOptionPane.showMessageDialog(frame,
							"Es ist ein Fehler aufgetreten.", "Fehler",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
			} else {
				return;
			}
		}
		Document currentHero = getAction().getSelectedHeld();
		HeroPrinter hp = new HeroPrinter(getAction().getPluginPath(), "DSA41");
		hp.fillForm(currentHero, System.getProperty("user.home"));
		JOptionPane.showMessageDialog(frame,
				"Die Datei wurde erstellt.", "Fertig",
				JOptionPane.INFORMATION_MESSAGE);
	}

	private List<String> checkDependancies() {
		String libPath = getAction().getPluginPath() + "/lib";
		File libDir = new File(libPath);
		if (!libDir.exists()) {
			libDir.mkdir();
		}
		String[] jars = libDir.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".jar");
			}
		});

		ArrayList<String> neededJars = new ArrayList<String>(
				Arrays.asList(dependantJars));
		for (String jar : jars) {
			if (neededJars.contains(jar))
				neededJars.remove(jar);
		}
		return neededJars;
	}

	private boolean downloadLibs(JFrame frame) {
		final String[] urls = {
				"http://sourceforge.net/projects/saxon/files/Saxon-HE/9.3/saxonhe9-3-0-5j.zip",
				"http://sourceforge.net/projects/itext/files/iText/iText5.1.2/itext-5.1.2.zip",
				"http://sourceforge.net/projects/ini4j/files/ini4j-bin/0.5.2/ini4j-0.5.2-bin.zip" };

		File tempDir = new File(getAction().getPluginPath() + "/temp");
		if(!tempDir.exists()){
			tempDir.mkdir();
		}
		DownloadDialog dl = new DownloadDialog(urls, tempDir.getAbsolutePath());
				
		if(!dl.downloadUrls())
			return false;
		
		File[] zips = tempDir.listFiles(new FilenameFilter() {			
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".zip");
			}
		});
		
		if(!extractZips(zips))				
			return false;

		File mappingsDir = new File(getAction().getPluginPath() + "/mappings");
		if(!mappingsDir.exists())
			mappingsDir.mkdir();
		
		dl.setUrls(new String[]{"http://helden-software-pdf-plugin.googlecode.com/hg/mappings/DSA41.ini"});
		dl.setOutputPath(mappingsDir.getAbsolutePath());
		if(!dl.downloadUrls())
			return false;
		
		
		return true;

	}

	private boolean extractZips(File[] zips) {
		try{
		for (File zip : zips) {
			ZipInputStream zipstream = new ZipInputStream(new FileInputStream(zip));
			ZipEntry zipEntry = null;
			while ((zipEntry = zipstream.getNextEntry()) != null) {
				FileOutputStream fos;
				if (zipEntry.getName().toLowerCase().endsWith(".jar")) {
					String fileName = zipEntry.getName();
					if(fileName.indexOf('/') != -1){
						fileName = fileName.substring(fileName.indexOf('/') + 1);
					}
					fos = new FileOutputStream(getAction().getPluginPath()
							+ "/lib/" + fileName);
				} else {
					fos = new FileOutputStream(File.createTempFile("helden",
							"temp"));
				}

				byte[] buffer = new byte[4096];
				int read = 0;
				while ((read = zipstream.read(buffer)) != -1) {
					fos.write(buffer, 0, read);
				}
				fos.close();
			}
		}
		}catch(Exception ex){
			Logger.getLogger(HeldenStart.class.getName()).log(Level.SEVERE,
					null, ex);
			return false;
		}
		return true;
	}

	@Override
	public ImageIcon getIcon() {
		return null;
	}

	@Override
	public String getMenuName() {
		return "Export auf aktuellem Sheet";
	}

	@Override
	public String getToolTipText() {
		return null;
	}

	@Override
	public String getType() {
		return SIMPLE;
	}

	public Action getAction() {
		if (action == null)
			action = new Action();

		return action;
	}
}
